package bma.common.langutil.objrouter.impl;

import java.util.List;
import java.util.Map;

import bma.common.langutil.core.HashAlgorithm;
import bma.common.langutil.objrouter.Const;

public class HashObjRouter extends BaseObjRouter {

	final org.slf4j.Logger log = org.slf4j.LoggerFactory
			.getLogger(HashObjRouter.class);

	private HashAlgorithm hashFunction = HashAlgorithm.CRC_HASH;

	public HashAlgorithm getHashFunction() {
		return hashFunction;
	}

	public void setHashFunction(HashAlgorithm hashFunction) {
		this.hashFunction = hashFunction;
	}

	public void setHashType(String s) {
		this.hashFunction = HashAlgorithm.valueOf(s);
	}

	@Override
	public Object dispath(Map<String, Object> options) {

		if (options == null) {
			throw new NullPointerException("[HashObjRouter] options is null !!");
		}
		if (options.get(Const.OBJ_ROUTER_SHARD_BY) == null) {
			throw new NullPointerException(
					"[HashObjRouter] options miss shardBy !!");
		}
		if (Objects == null || Objects.size() == 0) {
			throw new NullPointerException("[HashObjRouter] objects not set !!");
		}

		Object shardBy = options.get(Const.OBJ_ROUTER_SHARD_BY);

		long hash = hashFunction.hash(shardBy.toString());
		int nodeIndex = (int) (hash % Objects.size());

		if (log.isDebugEnabled()) {
			log.debug("hash({}) => {}", hash, nodeIndex);
		}
		return Objects.get(nodeIndex);
	}

	public List<Object> Objects;

	public List<Object> getObjects() {
		return Objects;
	}

	public void setObjects(List<Object> objects) {
		Objects = objects;
	}

}
